package com.zbkj.admin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.zbkj.admin.request.BaseUploadRequest;
import com.zbkj.admin.result.CommonResult;
import com.zbkj.admin.vo.FileResultVo;
import com.zbkj.admin.service.UploadService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.*;


/**
 * 上传文件 前端控制器 -- 用户端
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Slf4j
@RestController
@RequestMapping("api/front/upload")
@Tag(name = "用户上传文件")
public class UserUploadFrontController {

    @Autowired
    private UploadService uploadService;

    @Operation(summary = "图片上传")
    @RequestMapping(value = "/image", method = RequestMethod.POST)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "model", value = "模块 用户user,商品product,微信wechat,news文章"),
//            @ApiImplicitParam(name = "pid", value = "分类ID 0编辑器,1商品图片,2拼团图片,3砍价图片,4秒杀图片,5文章图片,6组合数据图,7前台用户,8微信系列 ", allowableValues = "range[0,1,2,3,4,5,6,7,8]")
//    })
    public CommonResult<FileResultVo> image(@RequestParam("multipart") MultipartFile multipart, @RequestParam(value = "model") String model,
                                            @RequestParam(value = "pid") Integer pid) {

        return CommonResult.success(uploadService.imageUpload(multipart, model, pid, null));
    }

    @Operation(summary = "文件上传")
    @RequestMapping(value = "/file", method = RequestMethod.POST)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "model", value = "模块 用户user,商品product,微信wechat,news文章"),
//            @ApiImplicitParam(name = "pid", value = "分类ID 0编辑器,1商品图片,2拼团图片,3砍价图片,4秒杀图片,5文章图片,6组合数据图,7前台用户,8微信系列 ", allowableValues = "range[0,1,2,3,4,5,6,7,8]")
//    })
    public CommonResult<FileResultVo> file(MultipartFile multipart, @RequestParam(value = "model") String model,
                                           @RequestParam(value = "pid") Integer pid) {
        return CommonResult.success(uploadService.fileUpload(multipart, model, pid, null));
    }

    @Operation(summary = "base64图片上传")
    @RequestMapping(value = "/base64", method = RequestMethod.POST)
    public CommonResult<FileResultVo> base64Upload(@RequestBody @Validated BaseUploadRequest request) {
        return CommonResult.success(uploadService.base64Upload(request.getBase64Url(), request.getModel(), request.getPid()));
    }

    // 拆分图片
    @GetMapping("/splitImage")
    @Operation(summary = "拆分图片")
    public CommonResult<List<String>> splitImage(@RequestParam("imageUrl") String imageUrl) {
        try {
            // 读取图片
            BufferedImage image = ImageIO.read(new URL(imageUrl));
            // 分割图片
            return CommonResult.success(splitImage(image, 3, 2));
        } catch (IOException e) {
            log.error("图片解析失败", e);
            return CommonResult.failed(e.getMessage());
        }
    }

    // 拆分图片
    @PostMapping("/splitImages")
    @Operation(summary = "拆分图片")
    public CommonResult<Map<String, List<String>>> splitImage(@RequestBody List<Map<String, String>> imageUrls) {
        // 判断拆分图片列表是否存在数据
        if (CollUtil.isNotEmpty(imageUrls)) {
            Map<String, List<String>> returnMap = new HashMap<>();
            // 循环获取分解图片
            for (Map<String, String> imageMap : imageUrls) {
                if (StrUtil.isEmpty(imageMap.get("id")) || StrUtil.isEmpty(imageMap.get("imageUrl"))) {
                    break;
                } else {
                    try {
                        // 读取图片
                        BufferedImage image = ImageIO.read(new URL(imageMap.get("imageUrl")));
                        // 分割图片
                        returnMap.put(imageMap.get("id"), splitImage(image, 2, 3));
                    } catch (IOException e) {
                        log.error("图片拆分失败", e);
                        return CommonResult.failed("图片拆分失败");
                    }
                }
            }
            ;
            return CommonResult.success(returnMap);
        }
        return CommonResult.failed("未找到数据");
    }

    public List<String> splitImage(BufferedImage originalImage, int rows, int cols) {
        int width = originalImage.getWidth();
        int height = originalImage.getHeight();
        int cellWidth = width / cols;
        int cellHeight = height / rows;

        try {
            List<String> base64ImageList = new ArrayList<>();
            for (int row = 0; row < rows; row++) {
                for (int col = 0; col < cols; col++) {
                    int x = col * cellWidth;
                    int y = row * cellHeight;
                    BufferedImage smallImage = originalImage.getSubimage(x, y, cellWidth, cellHeight);

                    // 处理小图片，例如保存到文件或转换为Base64等
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ImageIO.write(smallImage, "png", baos); // 可以改为其他格式，如jpg等
                    byte[] imageInByte = baos.toByteArray();
                    String base64String = Base64.getEncoder().encodeToString(imageInByte);

                    base64ImageList.add(base64String);
                }
            }
            return base64ImageList;
        } catch (Exception e) {
            log.error("图片拆分失败", e);
            return null;
        }
    }
}



